-module(toplevel).
-include_lib ("nitrogen/include/wf.inc").
-include ("useful.hrl").
-compile(export_all).

start() ->
    spawn(toplevel, loop, [dict:new()]).

loop(Dict) ->
    receive 
	{talk, From, ID, Message} -> 
	    case dict:find(ID, Dict) of
		{ok, Port} -> 
		    From ! {ok, talk:say(Port, Message)},
		    loop(Dict);
		error -> 
		    From ! error,
		    loop(Dict)
	    end;
	{add, From, ID} ->
	    case dict:find(ID, Dict) of
		{ok, _} -> 
		    From ! {error, already_connected},
		    loop(Dict);
		error -> 
		    From ! ok,
		    loop(dict:append(ID, talk:hi(?HERTZ_TOPLEVEL_PATH), Dict))
	    end;
	{remove, From, ID} ->
	    case dict:find(ID, Dict) of
		{ok, Port} ->
		    talk:bye(Port),
		    From ! ok,
		    loop(dict:erase(ID,  Dict));
		_ ->
		    From ! {error, not_connected},
		    loop(Dict)
	    end
    end.
